<script lang="tsx">
import { computed, defineComponent, ref, unref } from 'vue'
import type { DescItem, DescriptionActionType, DescriptionProps } from './type'
import { basicDescriptionProps } from './props'
import { ElDescriptions, ElDescriptionsItem } from 'element-plus'
import { isArray, isBoolean, isFunction, isPlainObject, isString } from 'lodash-es'
import { getSlot } from '@/components/BasicForm/src/common/helper'
import type { Recordable } from '@/types/global'
import RenderPdfBtn from './components/RenderPdfBtn.vue'

export default defineComponent({
  emits: ['register'],
  props: basicDescriptionProps,
  setup(props, { emit, attrs, slots }) {
    const propsRef = ref<Partial<DescriptionProps>>({})
    const getBindValue = computed(
      () => ({ ...attrs, ...props, ...propsRef.value }) as DescriptionProps,
    )
    const getSchemaProps = computed(() => unref(getBindValue).schema || [])
    const getDataProps = computed(() => unref(getBindValue).data || {})
    async function setProps(descrProps: Partial<DescriptionProps>) {
      propsRef.value = { ...unref(propsRef), ...descrProps }
    }
    const methods: Partial<DescriptionActionType> = {
      setProps,
    }
    // 是否显示相关
    function getShow(schema: DescItem): boolean {
      const { show } = schema
      let isShow = true
      if (isFunction(show)) {
        isShow = show(getDataProps.value)
      } else if (isBoolean(show)) {
        isShow = show
      }
      return isShow
    }

    // 渲染pdf
    function renderPdf(schema: DescItem) {
      const { field, pdfConfig } = schema

      let dataOne: any = unref(getDataProps)[field as string]
      // console.log('渲染pdf', isArray(unref(dataOne)), isPlainObject(unref(dataOne)), isString(unref(dataOne)));

      if (dataOne && isString(dataOne)) {
        // console.log('字符串');

        let url = dataOne
        let name = url.split('/').pop() || ''
        return (
          <div class="inline-block">
            <RenderPdfBtn fileName={name} path={url} {...pdfConfig} />
          </div>
        )
      } else if (dataOne && isPlainObject(unref(dataOne))) {
        // console.log('对象');

        return (
          <div class="inline-block">
            <RenderPdfBtn
              fileName={(dataOne as any).fileName}
              path={(dataOne as any).path}
              {...pdfConfig}
            />
          </div>
        )
      } else if (dataOne && isArray(dataOne)) {
        // 数组
        return (
          <div class="inline-block">
            <div class="flex flex-col">
              {(dataOne as any[]).map((item: Recordable, index: number) => {
                return (
                  <RenderPdfBtn
                    fileName={item.fileName}
                    path={item.path}
                    class={[index + 1 != dataOne.length ? 'mb-[12px]' : '']}
                    {...pdfConfig}
                  />
                )
              })}
            </div>
          </div>
        )
      } else {
        return '--'
      }
    }

    // 渲染field相关
    function renderComponent(schema: DescItem) {
      const { imageClass: bimageClass } = getBindValue.value
      const { field, type, imageClass } = schema
      let fileType: string | undefined = ''
      let url = unref(getDataProps)[field as string]
      let imageclassd = imageClass || bimageClass || ''
      if (type == 'auto') {
        // 根据文件名称识别文件类型
        const imgExtensions = /\.(jpeg|jpg|gif|png|bmp|webp|svg)$/i
        if (imgExtensions.test(url)) {
          fileType = 'image'
        } else if (url.indexOf('.pdf') > -1) {
          fileType = 'pdf'
        }
      } else {
        fileType = type
      }

      let renderd: any
      if (fileType == 'image') {
        // 图片
        renderd = (
          <el-image
            class={imageclassd}
            src={url}
            fit="cover"
            zoom-rate={1.2}
            max-scale={7}
            min-scale={0.2}
            preview-src-list={[url]}
            hide-on-click-modal
          />
        )
      } else if (fileType == 'imageArr') {
        // 图片数组
        renderd = unref(getDataProps)[field as string].map((e: string, i: number) => {
          return (
            <el-image
              class={imageclassd}
              src={e}
              fit="cover"
              zoom-rate={1.2}
              max-scale={7}
              min-scale={0.2}
              preview-src-list={unref(getDataProps)[field as string]}
              initial-index={i}
              hide-on-click-modal
            />
          )
        })
      } else if (fileType == 'pdf') {
        // pdf
        renderd = renderPdf(schema)
      } else {
        renderd = unref(getDataProps) && field && url ? url : '--'
      }
      return renderd
    }

    // 渲染内容
    function renderItem(schema: DescItem) {
      const { colon: pColon } = getBindValue.value
      const { colon, label, slotLabel, renderLabel, field, slot, render } = schema
      let val = field ? getDataProps.value[field] : ''
      let renderd: any
      // 渲染label
      if (slotLabel) {
        renderd = {
          ...renderd,
          label: () => getSlot(slots, slotLabel, { val, data: unref(getDataProps) }),
        }
      } else if (renderLabel) {
        renderd = {
          ...renderd,
          label: () =>
            isFunction(renderLabel) ? renderLabel(val, unref(getDataProps)) : renderLabel,
        }
      } else {
        // 是否显示冒号
        let colond = false
        // 全局
        if (isBoolean(pColon)) {
          colond = pColon
        }
        // 局部
        if (isBoolean(colon)) {
          colond = colon
        }
        const labeld = colond ? label + ':' : label
        renderd = {
          ...renderd,
          label: () => labeld,
        }
      }
      // 渲染field
      if (slot) {
        renderd = {
          ...renderd,
          default: () => getSlot(slots, slot, { val, data: unref(getDataProps) }),
        }
      } else if (render) {
        renderd = {
          ...renderd,
          default: () => (isFunction(render) ? render(val, unref(getDataProps)) : render),
        }
      } else {
        renderd = {
          ...renderd,
          default: () => renderComponent(schema),
        }
      }

      return renderd
    }

    // 渲染 DescriptionsItem
    function renderDescriptions() {
      return getSchemaProps.value.map((e: DescItem) => {
        return getShow(e) ? (
          <ElDescriptionsItem {...e} v-slots={renderItem(e)}></ElDescriptionsItem>
        ) : null
      })
    }
    // 渲染 Descriptions 自定义区域
    function renderDescrCustom() {
      const { slotExtra, slotTitle, renderExtra, renderTitle } = unref(getBindValue)
      let renderd: any
      if (slotExtra) {
        renderd = {
          ...renderd,
          extra: () => getSlot(slots, slotExtra),
        }
      } else if (renderExtra) {
        renderd = {
          ...renderd,
          extra: () => (isFunction(renderExtra) ? renderExtra() : renderExtra),
        }
      }

      if (slotTitle) {
        renderd = {
          ...renderd,
          title: () => getSlot(slots, slotTitle),
        }
      } else if (renderTitle) {
        renderd = {
          ...renderd,
          title: () => (isFunction(renderTitle) ? renderTitle() : renderTitle),
        }
      }

      return renderd
    }

    emit('register', methods)

    return () => {
      return (
        <ElDescriptions {...getBindValue.value} v-slots={renderDescrCustom()}>
          {renderDescriptions()}
        </ElDescriptions>
      )
    }
  },
})
</script>
